/*
 * Put script at the end of the html.
 * <script src="editor.js"></script>
 *
 * Editor defined by code tag with attributes
 */
var editor = CodeMirror.fromTextArea (document.getElementById("code"),
{
  addModeClass: true,
  indentWithTabs: false,
  lineNumbers: true,
  mode: "clike",
  smartIndent: true,
  tabSize: 2,
  theme: "rubyblue",
  value: code.value,
});

var folder = "My Projects/";
var lastfile;

/*
 * Need to run a polling timer for longer commands.
 */
var pollvar;
var pollrun;

/*
 * Load defaults.
 */
var startup=true;

function loadpage()
{
  getDir(folder);
}

/*
 * Support functions
 */
function newXmlHttp()
{
  var xmlhttp;
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else {
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  return xmlhttp;
}

function getDir (fileName)
{
  var stat = document.getElementById("status");
  stat.innerHTML = "File List";
  var files = document.getElementById("filefolder");

  var xmlhttp = newXmlHttp();
  xmlhttp.open("GET", "/FileList/"+fileName, true);
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
      var string=xmlhttp.responseText;
      files.innerHTML = string;
      if(startup) {
        getFile("My Projects/"+files.options[0].innerHTML);
        startup=false;
      }
      var file = document.getElementById("filename");
      file.innerHTML = fileName;

      var zombie = document.getElementById("zombie");
      zombie.style.visibility="hidden";

      if (lastfile) {
        setSelectedFile(lastfile);
      }
    }
  }
  xmlhttp.send();
}

function deleteFile (fileName)
{
  clearSize();
  var stat = document.getElementById("status");
  stat.innerHTML = "Delete File";

  var xmlhttp = newXmlHttp();
  xmlhttp.open("POST", "/DeleteFile/"+fileName, true);
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
      var file = document.getElementById("filename");
      file.innerHTML = "Deleted "+fileName;
      var files = document.getElementById("filefolder");
      lastfile = 0;
      getDir(folder);
      getFile(folder+files.options[0].innerHTML);
    }
  }
  xmlhttp.send(fileName);
}

function getFile (fileName)
{
  clearSize();
  var stat = document.getElementById("status");
  stat.innerHTML = "Open File";

  var xmlhttp = newXmlHttp();
  xmlhttp.open("GET", "/OpenFile/"+fileName, true);
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
      var string=xmlhttp.responseText;
      editor.doc.setValue(string);
      var file = document.getElementById("filename");
      file.innerHTML = fileName;
    }
  }
  xmlhttp.send();
}

function saveFile (fileName)
{
  clearSize();
  var stat = document.getElementById("status");
  stat.innerHTML = "Save File";

  var xmlhttp = newXmlHttp();
  xmlhttp.open("PUT", "/SaveFile/"+fileName, true);
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
      var file = document.getElementById("filename");
      file.innerHTML = fileName;
    }
  }
  xmlhttp.send(editor.doc.getValue());
}

function saveBuildFile (fileName)
{
  clearSize();
  var stat = document.getElementById("status");
  stat.innerHTML = "Save File";

  var xmlhttp = newXmlHttp();
  xmlhttp.open("PUT", "/SaveFile/"+fileName, true);
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
      var file = document.getElementById("filename");
      file.innerHTML = fileName;
      buildFile(fileName);
    }
  }
  xmlhttp.send(editor.doc.getValue());
}

function clearSize()
{
  var size = document.getElementById("sizeid");
  size.innerHTML = "";
}

function sizeResult ()
{
  var size = document.getElementById("sizeid");
  size.innerHTML = " ";

  var xmlhttp = newXmlHttp();
  xmlhttp.open("POST", "/SizeResult/", true);
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
      var s = xmlhttp.responseText;
      var a = s.split("\n");
      if (a.length > 0) {
        var s2 = a[1];
        s2 = s2.trim();
        //size.innerHTML = s2;
        var a2 = s2.split('\t');
        var m = 0;
        for (var n = 0; n < a2.length; n++) {
          if (a2[n]) {
            m++;
          }
          if (m == 3) {
            size.innerHTML = a2[m].trim() + " Bytes";
            break;
          }
        }
      }
    }
  }
  xmlhttp.send("size");
}

function buildFile (fileName)
{
  clearSize();
  var stat = document.getElementById("status");
  stat.innerHTML = "Build ";

  var xmlhttp = newXmlHttp();
  xmlhttp.open("POST", "/Build/"+fileName, true);
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
      var file = document.getElementById("filename");
      file.innerHTML = "Build "+fileName;
      var string=xmlhttp.responseText;
      stat.innerHTML = string;
    }
  }
  xmlhttp.send("build");
}


function buildResult (fileName)
{
  if (!pollrun++) return;
  clearSize();
  var stat = document.getElementById("status");
  stat.innerHTML += ".";

  var xmlhttp = newXmlHttp();
  xmlhttp.open("POST", "/BuildResult/"+fileName, true);
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
      var string=xmlhttp.responseText;
      if (string) {
        if (pollvar) {
          clearInterval(pollvar);
          pollvar = 0;
        }

        // update status, then show alert
        if(string == "Build Succeeded!") {
          stat.innerHTML = string;
          sizeResult();
        }
        else {
          stat.innerHTML = "Build Failed.";
          alert(string);
        }
      }
    }
  }
  xmlhttp.send();
}

/*
var waitvar;
function wait ()
{
  if (waitvar) {
    clearInterval(waitvar);
    waitvar = 0;
  }
}
*/

function loadResult (fileName)
{
  if (!pollrun++) return;
  clearSize();
  var stat = document.getElementById("status");
  stat.innerHTML += ".";

  var xmlhttp = newXmlHttp();
  xmlhttp.open("POST", "/LoadResult/"+fileName, true);
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
      var string=xmlhttp.responseText;
      if (string) {
        // update status, then show alert
        if(string == "Load Succeeded!") {
          stat.innerHTML = string;
        }
        else {
          stat.innerHTML = "Load Failed.";
          alert(string);
        }

        if (pollvar) {
          clearInterval(pollvar);
          pollvar = 0;
        }

      }
    }
  }
  xmlhttp.send("load result");
}

function loadRAM (fileName)
{
  clearSize();
  var file = document.getElementById("filename");
  var stat = document.getElementById("status");
  stat.innerHTML = "Load RAM";

  var xmlhttp = newXmlHttp();
  xmlhttp.open("POST", "/LoadRAM/"+fileName, true);
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
      file.innerHTML = fileName;
      stat.innerHTML = "Loading RAM .";
    }
  }
  xmlhttp.send("load ram");
}

function loadEEPROM (fileName)
{
  clearSize();
  var file = document.getElementById("filename");
  var stat = document.getElementById("status");
  stat.innerHTML = "Load EEPROM";

  var xmlhttp = newXmlHttp();
  xmlhttp.open("POST", "/LoadEEPROM/"+fileName, true);
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
      file.innerHTML = fileName;
      stat.innerHTML = "Loading EEPROM .";
    }
  }
  xmlhttp.send("load eeprom");
}

function getserver(command, elementid)
{
  var xmlhttp = newXmlHttp();
  xmlhttp.open("GET", command, true);
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
      var string=xmlhttp.responseText;
      document.getElementById(elementid).innerHTML=string;
      var stat = document.getElementById("status");
      stat.innerHTML = string;
    }
  }
  xmlhttp.send();
}

function setSelectedFile(filename) {
  var files = document.getElementById("filefolder");
  var index = files.selectedIndex;
  for (var n = 0; n < files.options.length; n++) {
    if (files.options[n].innerHTML.match(filename) == filename) {
      files.selectedIndex = n;
      var stat = document.getElementById("status");
      stat.innerHTML += ": index "+n;
      return;
    }
  }
  files.selectedIndex = index;
}

function DirLoad ()
{
  getDir(folder);
}

function FileLoad ()
{
  if (pollvar) return;
  var stat = document.getElementById("status");
  stat.innerHTML = "Load File";
  var input = document.getElementById("filefolder");
  var file = input.options[input.selectedIndex].innerHTML;
  getFile(folder+file);
}

function FileDelete ()
{
  if (pollvar) return;
  var stat = document.getElementById("status");
  stat.innerHTML = "Delete File";
  var files = document.getElementById("filefolder");
  deleteFile(folder+files.options[files.selectedIndex].innerHTML);
}

function FileSave ()
{
  if (pollvar) return;
  var stat = document.getElementById("status");
  stat.innerHTML = "Save File";
  var files = document.getElementById("filefolder");
  saveFile(folder+files.options[files.selectedIndex].innerHTML);
}

function FileSaveAs ()
{
  if (pollvar) return;
  var stat = document.getElementById("status");
  stat.innerHTML = "Save As File";
  var filename = prompt("Enter new file name:", "");
  if (filename) {
    lastfile = filename;
    saveFile(folder+filename);
    getDir(folder);
  }
}

function Build ()
{
  if (pollvar) return;
  var stat = document.getElementById("status");
  stat.innerHTML = "Build";
  var files = document.getElementById("filefolder");
  //saveBuildFile(folder+files.options[files.selectedIndex].innerHTML);
  buildFile(folder+files.options[files.selectedIndex].innerHTML);

  pollrun = 0;
  pollvar = setInterval(buildResult, 500);
}

function LoadRAM ()
{
  if (pollvar) return;
  var stat = document.getElementById("status");
  stat.innerHTML = "LoadRAM";

  var files = document.getElementById("filefolder");
  loadRAM(folder+files.options[files.selectedIndex].innerHTML);

  pollrun = 0;
  pollvar = setInterval(loadResult, 500);
}

function LoadEEPROM ()
{
  if (pollvar) return;
  var stat = document.getElementById("status");
  stat.innerHTML = "LoadEEPROM";

  var files = document.getElementById("filefolder");
  loadEEPROM(folder+files.options[files.selectedIndex].innerHTML);

  pollrun = 0;
  pollvar = setInterval(loadResult, 1000);
}

//
// Not implemented yet. Most likely will become a separate page.
//
function Debug ()
{
  if (pollvar) return;
  var stat = document.getElementById("status");
  stat.innerHTML = "Debug";
}


//
// Let user choose this on startup.
//
var toolColor = [
  /* theme name           toolbar bgcolor   body bgcolor */
  /* rubyblue */          "LightSlateGray", "LightSlateGray",
  /* 3024-day */          "Bisque",         "Bisque",
  /* 3024-night */        "BurlyWood",      "BurlyWood",
  /* ambiance */          "LightGray",      "LightGray",
  /* ambiance-mobile */   "LightGray",      "LightGray",
  /* base16-dark */       "Bisque",         "Bisque",
  /* base16-light */      "Bisque",         "Bisque",
  /* blackboard */        "#0A0A2D",        "LightGray",
  /* cobalt */            "#002240",        "LightSteelBlue",
  /* eclipse */           "LightGray",      "LightGray",
  /* elegant */           "LightGray",      "LightGray",
  /* erlang-dark */       "LightSlateGray", "LightSlateGray",
  /* lesser-dark */       "Bisque",         "Bisque",
  /* mbo */               "LightGray",      "LightGray",
  /* mdn-like */          "#008ab8",        "LightGray",
  /* midnight */          "LightGray",      "LightGray",
  /* monokai */           "#2b5200",        "#2b5200",
  /* neat */              "#986",           "#986",
  /* neo */               "LightGray",      "LightGray",
  /* night */             "White",          "White",
  /* paraiso-dark */      "#809980",        "#809980",
  /* paraiso-light */     "#809980",        "#809980",
  /* pastel-on-dark */    "#E0EBFF",        "#E0EBFF",
  /* rubyblue */          "LightSlateGray", "LightSlateGray",
  /* solarized dark */    "LightSlateGray", "LightSlateGray",
  /* solarized light */   "Ivory",          "Ivory",
  /* the-matrix */        "Black",          "Black",
  /* twilight */          "DimGray",        "DimGray",
  /* vibrant-ink */       "LightGray",      "LightGray",
  /* xq-dark */           "#080020",        "#080020",
  /* xq-light */          "White",          "White",
];

function selectTheme() {
  var input = document.getElementById("theme");
  var theme = input.options[input.selectedIndex].innerHTML;
  editor.setOption("theme", theme);
  var el = document.getElementById("toolbar");
  el.style.backgroundColor = toolColor[input.selectedIndex*2];
  var bg = document.getElementById("body");
  bg.style.backgroundColor = toolColor[input.selectedIndex*2+1];
}






